<?php

namespace app\api\controller;

use app\api\model\User as UserModel;
use app\api\model\UserCoupon;
use app\api\model\UserCoupon as UserCouponModel;
use app\common\model\Wxapp as WxappModel;
use app\agentapi\controller\Weixin as WeixinModel;
use think\Db;
use org\Redis;
/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends Controller
{
    /*
     * 微信小程序获取用户手机号
     */
    public function getUserMobile(){
        $token=input('token');
        $encryptedData = input('encryptedData');
        $iv = input('iv');
        $wxapp_id=input('wxapp_id');
        $redis = new Redis();
        $loginInfo=$redis->get($token);
        $weixinInfo=Db::name('wxapp')->where(['wxapp_id'=>$wxapp_id])->find();
        if(!$weixinInfo){
            return $this->renderError('未获取到小程序信息');
        }
        $appid =$weixinInfo['app_id'];
        $session_key =$loginInfo['session_key'];
        $openid=$loginInfo['openid'];
        $pc = new WeixinModel($appid, $session_key);
        $errCode=$pc->decryptData($encryptedData, $iv, $data);
        if ($errCode==0) {
            $numDatas = json_decode($data);
            $phone = $numDatas->phoneNumber;
            //更新用户手机号
            $userInfo = $this->getUser();
            Db::name('user')->where(['open_id'=>$openid])->update(['mobile'=>$phone]);
            Db::name('dealer_user')->where(['user_id'=>$userInfo['user_id']])->update(['mobile'=>$phone]);
            return $this->renderSuccess('更新手机号码成功');
        } else {
            return $this->renderError('更新手机号失败，请手动输入手机号进行绑定');
        }
    }
    /*
     * 授权获取手机号失败后手动输入手机号进行绑定
     */
    public function handToSetMobile(){
        $wxapp_id=input('wxapp_id');
        $weixinInfo=Db::name('wxapp')->where(['wxapp_id'=>$wxapp_id])->find();
        $phone=input('mobile');
        if(!$phone){
            return $this->renderError('请输入手机号');
        }
        //判断改手机号是否已经绑定
        $userInfos=Db::name('user')->where(['mobile'=>$phone])->field('user_id')->find();
        if($userInfos){
            return $this->renderError('该手机号已占用，请重新输入');
        }
        if(!$weixinInfo){
            return $this->renderError('未获取到小程序信息');
        }
        if(!preg_match("/^1((34[0-8]\d{7})|((3[0-3|5-9])|(4[5-7|9])|(5[0-3|5-9])|(66)|(7[2-3|5-8])|(8[0-9])|(9[1|8|9]))\d{8})$/", $phone)){
            return $this->renderError('请输入正确的手机号');
        }
        $userInfo = $this->getUser();
        $updUser=Db::name('user')->where(['user_id'=>$userInfo['user_id']])->update(['mobile'=>$phone]);
        $updDeaUser=Db::name('dealer_user')->where(['user_id'=>$userInfo['user_id']])->update(['mobile'=>$phone]);
        if($updDeaUser&&$updUser){
            return $this->renderSuccess('更新手机号码成功');
        }
        return $this->renderError('更新手机号码失败');
    }
    /**
     * 用户自动登录
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login()
    {
        $model = new UserModel;

        return $this->renderSuccess([
            'user_id' => $model->login($this->request->post()),
            'token' => $model->getToken(),
            'userInfo' => $model->getUser($model->getToken())
        ]);
    }

    /**
     * 当前用户详情
     * @return array
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function detail()
    {
        // 当前用户信息
        $userInfo = $this->getUser();
        return $this->renderSuccess(compact('userInfo'));
    }

    /**
     *获取用户可以使用的优惠券
     */
    public function getCoupon($price){

       $userInfo = $this->getUser();
       $list=array_values(UserCouponModel::getUserCouponList($userInfo['user_id'],$price));
       if(count($list)==0){
           return $this->renderSuccess(0,'暂无优惠券');
       }else{
           return $this->renderSuccess($list);
       }
    }



    /**
     *检查是否有分销资格
     */
    public function checkDealer(){

        // 请求参数
        $param = $this->request->param();

        $type = isset($param['type']) ? $param['type'] : '';

        $userInfo = $this->getUser();

        $dealer_case = WxappModel::dealerCase($param['wxapp_id']);

        if($dealer_case==1){
            //检查用户是否有分销权限
            $checkDealeModel = new UserModel;

            $checkDealer = $checkDealeModel->getConfigByUserType($userInfo,$type);
            if ($checkDealer === false) {
                return $this->renderError($checkDealeModel->getError());
            }
        }
        return $this->renderSuccess([],'有分销资格');
    }
    /*
    * 微信授权登录
    */
    public function wxLogin(){
        $model=new UserModel;
        // 获取当前小程序信息
        return $this->renderSuccess([
            'user_id' => $model->weixinLogin($this->request->post()),
            'token' => $model->getToken(),
            'userInfo' => $model->getUser($model->getToken())
        ]);
    }

}
